<template>
	<div class="app-container">
		<div class="jcxx">
			<el-card class="box-card">
				<div slot="header" class="clearfix">
					<span>基础信息</span>
				</div>
				<div class="text item">
					<div>
						<el-form ref="outboundData" :rules="rules" :model="outboundData" size="small"
							label-width="100px" label-position="left">
							<el-row type="flex" justify="space-around" align="bottom">
								<el-col :span="10">
									<el-form-item label="出库单号" prop="outboundCode">
										<el-input v-model="outboundData.outboundCode" placeholder="自动获取系统编号"
											:disabled='true' :style="{ width: '100%' }"></el-input>
									</el-form-item>
								</el-col>
								<el-col :span="10">
									<el-form-item label="出库类型" prop="outboundType">
										<el-select @change="changeType" v-model="outboundData.outboundType"
											placeholder="请选择出库类型" clearable :style="{ width: '100%' }">
											<el-option v-for="dict in dict.type.py_outbound_type" :key="dict.value"
												:label="dict.label" :value="dict.value" />
										</el-select>
									</el-form-item>
								</el-col>
							</el-row>
							<el-row type="flex" justify="space-around" align="bottom">
								<el-col :span="10">
									<el-form-item label="仓库名称" prop="warehouseCode">
										<el-select v-model="outboundData.warehouseCode" placeholder="请选择"
											@change="warehouseChange" :style="{ width: '100%' }">
											<el-option v-for="item in warehouseOptions" :key="item.value"
												:label="item.lable" :value="item.value" />
										</el-select>
									</el-form-item>
								</el-col>
								<el-col :span="10">
									<el-form-item label="出库日期" prop="outboundTime">
										<el-date-picker v-model="outboundData.outboundTime" format="yyyy-MM-dd"
											value-format="yyyy-MM-dd" :style="{ width: '100%' }" placeholder="请选择">
										</el-date-picker>
									</el-form-item>
								</el-col>
							</el-row>
							<el-row type="flex" justify="space-around" align="bottom">
								<el-col :span="10">
									<el-form-item label="关联单号" prop="relatedNumber">
										<div style="display: flex; align-items: center;">

											<el-input v-model="outboundData.relatedNumber" placeholder="请输入"
												:style="{ width: '100%' }" disabled />
											<el-button style="padding-left: 10px;" type="text" @click="openForm">订单查看
											</el-button>
											<el-checkbox checked style="padding-left: 10px;">关联单号</el-checkbox>
										</div>
									</el-form-item>
								</el-col>
								<el-col :span="10">
									<el-form-item label="供应商" prop="relatedTarget">
										<el-input v-model="outboundData.relatedTarget" placeholder="请输入" disabled
											:style="{ width: '100%' }" />
									</el-form-item>
								</el-col>
							</el-row>
							<el-row type="flex" justify="space-around" align="bottom">
								<el-col :span="10">
									<el-form-item label="收货人" prop="consignee">
										<el-input v-model="outboundData.consignee" placeholder="请输入联系人" disabled
											:style="{ width: '100%' }">
										</el-input>
									</el-form-item>
								</el-col>
								<el-col :span="10">
									<el-form-item label="联系方式" prop="phone">
										<el-input v-model="outboundData.phone" placeholder="请输入" disabled
											:style="{ width: '100%' }"></el-input>
									</el-form-item>
								</el-col>
							</el-row>
							<el-row>
								<el-col :span="10" style="margin-left: 70px;padding-left: 5px;">
									<el-form-item label="经办人" prop="reviewer">
										<el-cascader
											:placeholder="outboundData.reviewer == null ? '请选择':outboundData.reviewer"
											:show-all-levels="false" :options="cascaderOptions" :props="cascaderProps"
											@change="handleCascaderChange" :style="{ width: '100%' }" />
									</el-form-item>
								</el-col>
							</el-row>
							<el-row style="margin-left: 70px; padding-left: 7px;">
								<el-form-item label=" 备注" prop="remark">
									<el-input v-model="outboundData.remark" type="textarea" placeholder="请输入"
										:maxlength="1000" :autosize="{ minRows: 4, maxRows: 10 }"
										:style="{ width: '100%' }"></el-input>
								</el-form-item>
							</el-row>
						</el-form>
					</div>

					<el-dialog :title="'选择进货退货单'" :visible.sync="openReturnForm" width="1150px" append-to-body>
						<el-divider></el-divider>
						<el-row :gutter="50">
							<el-col :span="18">
								<el-form :model="queryParamsReturn" size="small" :inline="true"
									v-show="receipts.showSearch" label-width="68px">
									<el-form-item prop="prCode">
										<el-input v-model="queryParamsReturn.prCode" placeholder="请输入单据编号" clearable />
									</el-form-item>
									<el-form-item prop="prState">
										<el-select v-model="queryParamsReturn.prState" placeholder="请选择单据状态" clearable>
											<el-option v-for="dict in dict.type.py_status_two" :key="dict.value"
												:label="dict.label" :value="dict.value" />
										</el-select>
									</el-form-item>
								</el-form>
							</el-col>
							<el-col :span="6">
								<el-button size="small">重置</el-button>
								<el-button type="success" size="small" @click="handleQueryReturn">搜索</el-button>
							</el-col>
						</el-row>

						<el-table @selection-change="handleSelectionInRejected" :data="receipts.receipts"
							ref="rejectedTable" style="width: 100%">
							<el-table-column type="selection" width="50" align="center" />
							<el-table-column align="center" :selectable="selectIsDisabled" prop="prId" label="序号"
								width="110" sortable />
							<el-table-column align="center" prop="prCode" label="退货单号" />
							<el-table-column label="单据状态" align="center" prop="receipts.prState" width="100">
								<template slot-scope="scope">
									<dict-tag :options="dict.type.py_status_two" :value="scope.row.prState" />
								</template>
							</el-table-column>
							<el-table-column align="center" prop="prTime" label="退货日期" width="110" />
							<el-table-column align="center" prop="supplier" label="供应商" width="110" />
							<el-table-column align="center" prop="phDept" label="进货部门" width="110" />
							<el-table-column align="center" prop="phPerson" label="进货人" width="110" />
							<el-table-column align="center" prop="rejectedNum" label="退货数量" width="110" />
							<el-table-column align="center" prop="rejectedMoney" label="退货金额" width="110" />
						</el-table>

						<pagination v-show="receipts.dataTotal > 0" :total="receipts.dataTotal"
							:page.sync="queryParamsReturn.pageNum" :limit.sync="queryParamsReturn.pageSize"
							@pagination="getInRejectedList" />
						<el-divider></el-divider>
						<span slot="footer" class="dialog-footer">
							<el-button @click="closeRejected">取 消</el-button>
							<el-button type="primary" @click="handleInRejected">确 定</el-button>
						</span>

					</el-dialog>

					<el-dialog :title="'选择销售出库单'" :visible.sync="openOutForm" width="1150px" append-to-body>
						<el-divider></el-divider>
						<el-row :gutter="50">
							<el-col :span="18">
								<el-form :model="queryParamsOut" size="small" :inline="true"
									v-show="receipts.showSearch" label-width="68px">
									<el-form-item prop="saleCode">
										<el-input v-model="queryParamsOut.saleCode" placeholder="请输入单据编号" clearable />
									</el-form-item>
									<el-form-item prop="saleState">
										<el-select v-model="queryParamsOut.saleState" placeholder="请选择单据状态" clearable>
											<el-option v-for="dict in dict.type.py_status_two" :key="dict.value"
												:label="dict.label" :value="dict.value" />
										</el-select>
									</el-form-item>
								</el-form>
							</el-col>
							<el-col :span="6">
								<el-button size="small">重置</el-button>
								<el-button type="success" size="small" @click="handleQueryOut">搜索</el-button>
							</el-col>
						</el-row>

						<el-table @selection-change="handleSelectionOdSale" :data="receipts.receipts" ref="odSaleTable"
							style="width: 100%">
							<el-table-column type="selection" :selectable="selectIsDisabled" style="border-radius: 50%;"
								width="50" align="center" />
							<el-table-column align="center" prop="saleId" label="序号" width="110" sortable />
							<el-table-column align="center" prop="saleCode" label="销售单号" />
							<el-table-column label="单据状态" align="center" prop="receipts.saleState" width="100">
								<template slot-scope="scope">
									<dict-tag :options="dict.type.py_status_two" :value="scope.row.saleState" />
								</template>
							</el-table-column>
							<el-table-column align="center" prop="saleTime" label="销售日期" width="110" />
							<el-table-column align="center" prop="customer" label="客户" width="110" />
							<el-table-column align="center" prop="deptName" label="销售部门" width="110" />
							<el-table-column align="center" prop="salePerson" label="销售负责人" width="110" />
							<el-table-column align="center" prop="saleNum" label="销售数量" width="110" />
							<el-table-column align="center" prop="saleMoney" label="销售金额" width="110" />
						</el-table>

						<pagination v-show="receipts.dataTotal > 0" :total="receipts.dataTotal"
							:page.sync="queryParamsOut.pageNum" :limit.sync="queryParamsOut.pageSize"
							@pagination="getOdSaleList" />
						<el-divider></el-divider>
						<span slot="footer" class="dialog-footer">
							<el-button @click="closeOdSale">取 消</el-button>
							<el-button type="primary" @click="handleOdSale">确 定</el-button>
						</span>

					</el-dialog>


				</div>
			</el-card>

			<el-card class="box-card">
				<div slot="header" class="clearfix">
					<span>出库明细</span>
				</div>
				<div class="text item">
					<span>
						<el-button type="primary" icon="el-icon-plus" size="mini" @click="handleDetails">添加</el-button>
						<el-button type="danger" icon="el-icon-delete" size="mini" @click="removeCheck">删除</el-button>
					</span>
				</div>

				<div class="text item">
					<el-table ref="multipleTable" :data="selectDetailsData" style="width: 100%"
						@selection-change="handleDetailsChange">
						<el-table-column type="selection" width="55" />
						<el-table-column align="center" fixed type="index" label="序号" width="50" />
						<el-table-column align="center" fixed prop="productName" label="货品名称" width="120" />
						<el-table-column align="center" fixed prop="productCode" label="货品编号" width="170" />
						<el-table-column align="center" prop="productType" label="货品类型" width="100" />
						<el-table-column align="center" prop="productModel" label="规格型号" width="100" />
						<el-table-column align="center" prop="inventory" label="当前库存" width="100" />
						<el-table-column align="center" prop="shippedNum"
							:label="outboundData.outboundType == 0 ? '销售数量': '退货数量'" width="100" />
						<el-table-column align="center" prop="notShipped" label="未出库数量" width="100" />
						<el-table-column align="center" prop="shipped" label="已出库数量" width="100" />
						<!-- 库位选择下拉框 -->
						<el-table-column align="center" label="出库库位" width="120">
							<template slot-scope="scope">
								<el-select v-model="scope.row.locationCode" placeholder="请选择"
									@change="handleLocationChange(scope.row)">
									<el-option v-for="item in locationData" :key="item.value" :label="item.label"
										:value="item.value" />
								</el-select>
							</template>
						</el-table-column>
						<!-- 本次入库数量输入框 -->
						<el-table-column align="center" label="本次出库数量" width="120">
							<template slot-scope="scope">
								<el-input v-model="scope.row.outboundNumber" placeholder="请输入数量"
									@blur="validateQuantity(scope.row)"></el-input>
							</template>
						</el-table-column>
						<el-table-column align="center" prop="inPrice"
							:label="outboundData.outboundType == 0 ? '销售单价': '退货单价'" width="120" />
						<!-- 入库金额 -->
						<el-table-column align="center" prop="money"
							:label="outboundData.outboundType == 0 ? '销售金额': '退货金额'" width="120" />
						<!-- 批次号输入框 -->
						<el-table-column align="center" label="批次号" width="120">
							<template slot-scope="scope">
								<el-input v-model="scope.row.batchNumber" placeholder="请输入批次号"></el-input>
							</template>
						</el-table-column>

						<!-- 生产日期日期选择框 -->
						<el-table-column label="生产日期" width="150">
							<template slot-scope="scope">
								<el-date-picker v-model="scope.row.createDate" type="date" placeholder="选择日期"
									style="width: 100%;">
								</el-date-picker>
							</template>
						</el-table-column>
						<!-- 备注输入框 -->
						<el-table-column align="center" label="备注" width="120">
							<template slot-scope="scope">
								<el-input v-model="scope.row.remark" placeholder="请输入备注"></el-input>
							</template>
						</el-table-column>
						<el-table-column align="center" fixed="right" label="操作" width="120">
							<template slot-scope="scope">
								<el-button type="text" size="small" @click="removeCheck(scope.row)">
									移除
								</el-button>
							</template>
						</el-table-column>
					</el-table>
				</div>
				<div style="margin-top: 15px;font-size: 12px;">
					<div style="float: left;">合计</div>
					<div style="float: left;"></div>
					<div style="float: right;">未出库数量：<span style="color:orange;margin-right: 30px;">
							{{ outboundData.notShipped }}
						</span></div>
					<div style="float: right;">已出库数量：<span style="color:orange;margin-right: 30px;">
							{{ outboundData.shipped }}
						</span></div>
					<div style="float: right;">出库数量：<span style="color:orange;margin-right: 30px;">
							{{ outboundData.reviewerNumber }}
						</span></div>
					<div style="float: right;">销售金额：<span style="color:orange;margin-right: 30px;">
							{{ outboundData.reviewerMoney }}
						</span></div>
				</div>
				<div style="margin-top: 10px;"></div>
				<!-- //添加明细 -->
				<el-dialog title="添加货品" width="1150px" :visible.sync="openDetails">
					<el-row>
						<el-col :span="24">
							<div class="grid-content bg-purple-dark" style="margin-top: -30px;padding-left: 10px;">
								<span
									v-text="outboundData.outboundType == 0 ? '销售单号：' + receipts.dataCodes : '进货退货单号：' + receipts.dataCodes"></span>
							</div>
						</el-col>
					</el-row>
					<el-row>
						<el-col :span="24">
							<div class="grid-content bg-purple-dark">
								<!-- 销售出库 -->
								<el-form v-if="outboundData.outboundType == 0" :model="queryParamsOutDetails"
									size="small" :inline="true" label-width="68px">
									<el-form-item>
										<el-input v-model="queryParamsOutDetails.productCode" placeholder="请输入货品编号名称"
											clearable />
									</el-form-item>

									<el-form-item>
										<el-button type="primary" icon="el-icon-search" size="mini"
											@click="queryDetails">搜索</el-button>
										<el-button icon="el-icon-refresh" size="mini">重置</el-button>
									</el-form-item>
								</el-form>

								<!-- 进货退货 -->
								<el-form v-else :model="queryParamsReturnDetails" size="small" :inline="true"
									label-width="68px">
									<el-form-item>
										<el-input v-model="queryParamsReturnDetails.productCode" placeholder="请输入货品编号名称"
											clearable />
									</el-form-item>
									<el-form-item>
										<el-button type="primary" icon="el-icon-search" size="mini"
											@click="queryDetails">搜索</el-button>
										<el-button icon="el-icon-refresh" size="mini">重置</el-button>
									</el-form-item>
								</el-form>


							</div>
						</el-col>
					</el-row>
					<el-table ref="detailsTable" :data="detailsData" @selection-change="handleSelectionDetails">
						<el-table-column type="selection" :selectable="selectIsDisabled" width="50" align="center" />
						<el-table-column align="center" prop="productCode" label="货品编号" width="170" />
						<el-table-column align="center" prop="productName" label="货品名称" width="110" />
						<el-table-column align="center" prop="productModel" label="规格型号" width="110" />
						<el-table-column align="center" prop="unit" label="单位" width="110">
							<template slot-scope="scope">
								<span v-if="scope.row.unit == 0">台</span>
								<span v-else-if="scope.row.unit == 1">部</span>
								<span v-else-if="scope.row.unit == 2">个</span>
								<span v-else>{{scope.row.unit}}</span>
							</template>
						</el-table-column>
						<el-table-column align="center" prop="inPrice"
							:label="outboundData.outboundType == 0 ? '销售单价': '退货单价'" width="110" />
						<el-table-column align="center" prop="shippedNum"
							:label="outboundData.outboundType == 0 ? '销售数量': '退货数量'" width="110" />
						<el-table-column align="center" prop="shippedMoney"
							:label="outboundData.outboundType == 0 ? '销售金额': '退货金额'" width="110" />
						<el-table-column align="center" prop="shipped" label="已出库" width="110" />
						<el-table-column align="center" prop="notShipped" label="未出库" width="110" />
					</el-table>

					<div slot="footer" class="dialog-footer">
						<el-button @click="cancelSelection">取 消</el-button>
						<el-button type="primary" @click="enableSelection">确 定</el-button>
					</div>
				</el-dialog>
			</el-card>

			<el-card class="box-card">
				<div slot="header" class="clearfix">
					<span>上传附件</span>
				</div>
				<div class="text item">
					<el-upload class="upload-demo" :action="uploadImgUrl" :on-change="uploadChange"
						:file-list="fileList" :before-upload="beforeUpload" :headers="headers"
						:before-remove="beforeRemove" :on-remove="handleRemove">
						<el-button size="small" type="primary">上传</el-button>
						<div slot="tip" class="el-upload__tip">您可以上传doc, pdf, rar等格式的文件，单个文件上传最大200MB。</div>
					</el-upload>
				</div>
			</el-card>

			<el-footer class="fixed-footer">
				<el-button type="primary" @click="submitForm">保存</el-button>
				<el-button @click="ocClude">关闭</el-button>
				<!-- <el-button>保存并提交</el-button> -->
			</el-footer>
			<div style="margin-top: 50px;">1</div>
		</div>
	</div>




</template>
<script>
	import {
		selectAllSysDept,
		selectAllSysDeptByID,
		selectAllSysUserByParentId,
		listInRejected,
		listOdSale,
		listRejectedDetails,
		listOdSaleDetails,
		getCode,
		addOutbound,
		getOutbound,
		updateOutbound
	} from "@/api/outbound/outbound";

	import {
		listWarehouse, //获取仓库名
		selectLocation,
		getInventoryNumber,
		getAttachment,
	} from "@/api/warehouse/warehouse"

	import {
		addOutboundDetails,
		getDetails,
		delDetails,
	} from "@/api/outbound/outbound_details"

	import {
		getToken
	} from "@/utils/auth";
	export default {
		dicts: ['py_outbound_type', 'py_status_two'],
		components: {},
		props: [],
		data() {
			return {
				rules: {
					reviewer: [{
						required: true,
						message: "经办人不能为空",
						trigger: "blur"
					}],
					outboundType: [{
						required: true,
						message: "出库类型不能为空",
						trigger: "blur"
					}],
					warehouseCode: [{
						required: true,
						message: "仓库不能为空",
						trigger: "blur"
					}],
					relatedNumber: [{
						required: true,
						message: "关联单号不能为空",
						trigger: "blur"
					}],
				},
				outboundData: {
					codeId: null,
					number: null,
					outboundId: null,
					outboundCode: null,
					outboundType: null,
					outboundStatus: null,
					warehouseCode: null,
					outboundTime: null,
					relatedNumber: null,
					relatedTarget: null,
					consignee: null,
					phone: null,
					reviewer: null,
					reviewerReport: null,
					reviewerTime: null,
					reviewerNumber: 0,
					reviewerMoney: 0,
					notShipped: 0,
					shipped: 0,
					fileList: [],
				},
				cascaderOptions: [],
				cascaderProps: {
					value: 'value',
					label: 'label',
					children: 'children',
				},
				openReturnForm: false, //显示单据
				openOutForm: false, //显示单据
				// 查询进货退货单据
				queryParamsReturn: {
					pageNum: 1,
					pageSize: 10,
					prCode: null, //退货单号
					prState: null, //单据状态
					supplier: null, //供应商
					phPerson: null, //进货人
					phDept: null, //进货部门
					phDate: [], //进货日期
				},
				// 查询销售出库单据
				queryParamsOut: {
					pageNum: 1,
					pageSize: 10,
					saleCode: null, //销售出库单号
					saleState: null, //单据状态
					customer: null, //客户
					salePerson: null, //销售负责人
					saelDept: null, //进货部门
					saleDate: [], //销售日期
				},
				//储存选中的商品
				receipts: {
					receipts: [], //单据
					dataCodes: null, //确定选中的数据
					dataTotal: 0, // 单据总条数
					selectDataCodes: null, //选中的单据
					receiptsLoading: true, //单据遮罩层
					showSearch: true, //显示搜索条件
					tempData: [], //临时存储单据
				},
				//查询进货退货详细
				queryParamsReturnDetails: {
					prCode: null,
					productCode: null,
					unit: null,
				},
				//查询销售出库详细
				queryParamsOutDetails: {
					saleDetailsCode: null,
					productCode: null,
					unit: null,
				},
				openDetails: false, //添加商品遮罩
				detailsData: [], //商品详细数据
				selectDetailsData: [], //选中的商品
				warehouseOptions: [], //仓库
				locationData: [], //库位
				tempDetailsData: [], //临时存订单详细选中的值
				selectDetails: [], //勾选的详细商品
				uploadImgUrl: process.env.VUE_APP_BASE_API + "/file/upload",
				headers: {
					Authorization: "Bearer " + getToken()
				},
				fileList: [], // 已上传的文件列表
				edit: {
					outboundId: null,
					listSelectDetails: [],
				},
				isClick: true,
				isExist: [],
			}
		},
		computed: {

		},
		mounted() {
			this.$nextTick(() => {
				this.isEdit();
			});

		},
		created() {
			this.edit.outboundId = this.$route.query.outboundId;


			this.fetchWarehouse();
			this.fetchHandle();
		},
		methods: {
			async isEdit() {
				if (this.edit.outboundId == null) {
					getCode(3).then(response => {
						this.outboundData.outboundCode = response.sequence;
						this.outboundData.codeId = response.codeId;
						this.outboundData.number = response.number;
					})

					return;
				}

				//获取信息
				try {
					const response = await getOutbound(this.edit.outboundId);
					this.outboundData = response.data;
					this.outboundData.notShipped = 0;
					this.outboundData.shipped = 0;
					this.outboundData.reviewerNumber = 0;
					this.outboundData.reviewerMoney = 0;

					await this.warehouseChange();

					if (this.outboundData.outboundType == 0) {
						await this.getOdSaleList();

					} else {
						this.getInRejectedList();
					}

					//查询文件
					getAttachment(this.outboundData.outboundCode).then(response => {
						const attachment = response;

						this.fileList = [...attachment.flat().map(file => ({
							name: file.fileName,
							url: file.filePath,
							size: file.size
						})), ...this.fileList];
					});

					this.receipts.dataCodes = this.outboundData.relatedNumber;
					await this.queryDetails();

					try {
						const code = this.outboundData.outboundCode;
						const responses = await getDetails(code);
						this.isExist = responses;
						if (responses && responses.length > 0) {
							responses.forEach(item => {
								const product = this.detailsData.find(i => i.productCode === item.productCode);

								item = {
									inPrice: item.unitPrice,
									shippedNum: item.number,
									unit: item.productUnit,
									notShipped: product.notShipped,
									shipped: product.shipped,
									...item
								};

								this.edit.listSelectDetails.push(item);
							})

							this.selectDetailsData = this.edit.listSelectDetails;
						}

					} catch (error) {
						console.error('Error fetching outbound:', error);
					}

				} catch (error) {
					console.error('Error fetching outbound:', error);
				}

				//获取订单

			},
			//关闭
			ocClude() {
				const obj = {
					path: "/wms/outbound/outbound/index",
					query: {
						t: Date.now()
					}
				};
				this.$tab.closeOpenPage(obj);
			},
			//保存
			submitForm() {
				this.$refs['outboundData'].validate(valid => {
					if (valid) {
						if (!this.isClick) {
							this.$message.warning('请勿重复提交');
							return;
						}
						this.isClick = false;

						if (!this.selectDetails || this.selectDetails.length === 0) {
							this.$message({
								message: '请选择出库商品！',
								type: 'warning'
							});
							this.isClick = true;
							return;
						}

						const isLocation = this.selectDetails.some(item => item.locationCode === null);
						if (isLocation) {
							this.$message({
								message: '库位不能为空！',
								type: 'warning'
							});
							this.isClick = true;
							return;
						}

						const outboundNumber = this.selectDetails.some(item => item.outboundNumber === null);
						if (outboundNumber) {
							this.$message({
								message: '本次出库数量不能为空！',
								type: 'warning'
							});
							this.isClick = true;
							return;
						}

						const isMax = this.selectDetails.some(item => item.outboundNumber > item.inventory);
						if (isMax) {
							this.$message({
								message: '本次出库数量不能大于库存数量！',
								type: 'warning'
							});
							this.isClick = true;
							return;
						}

						const isMax2 = this.selectDetails.some(item => item.outboundNumber > item.notShipped);
						if (isMax2) {
							this.$message({
								message: '本次出库数量不能大于未出库数量！',
								type: 'warning'
							});
							this.isClick = true;
							return;
						}

						const isbatchNumber = this.selectDetails.some(item => item.batchNumber === null);
						if (isbatchNumber) {
							this.$message({
								message: '批次号不能为空！',
								type: 'warning'
							});
							this.isClick = true;
							return;
						}


						const isCreateDate = this.selectDetails.some(item => item.createDate === null);
						if (isCreateDate) {
							this.$message({
								message: '创建日期不能为空！',
								type: 'warning'
							});
							this.isClick = true;
							return;
						}
						//添加盘点单
						this.outboundData.fileList = this.fileList;

						if (this.outboundData.outboundType == '0') {
							this.selectDetails.forEach(item => {
								if (item.unit == '0') {
									item.unit = '台';
								}

								if (item.unit == '1') {
									item.unit = '部';
								}

								if (item.unit == '2') {
									item.unit = '个';
								}
							});
						}

						if (this.edit.outboundId != null) {
							const outboundCode = this.outboundData.outboundCode;

							if(this.isExist.length > 0){
								delDetails(outboundCode);
							}

							updateOutbound(this.outboundData).then(response => {
								this.selectDetails.forEach(item => {
									item = {
										unitPrice: item.inPrice,
										number: item.shippedNum,
										productUnit: item.unit,
										...item
									};
									addOutboundDetails(item).then(response => {
										console.log('提交成功');
									})
								});

								this.$modal.msgSuccess("保存成功");
								this.$router.push({
									path: '/wms/outbound/outbound/index'
								});
							}).catch(error => {
								this.isClick = true;
							});

							return;
						}

						addOutbound(this.outboundData).then(response => {
							this.selectDetails.forEach(item => {
								item = {
									unitPrice: item.inPrice,
									number: item.shippedNum,
									productUnit: item.unit,
									...item
								};
								addOutboundDetails(item).then(response => {
									console.log('提交成功');
								})
							});
							this.$modal.msgSuccess("保存成功");
							this.$router.push({
								path: '/wms/outbound/outbound/index'
							});
						}).catch(error => {
							this.isClick = true;
						});

					}
				});
			},
			handleCascaderChange(value) {
				// 通过change事件获取value，并在data中更新selectedLabel
				const selectedOption = this.cascaderOptions.find(option => option.value === value[0]).children
					.find(option => option.value === value[1]).children
					.find(option => option.value === value[2]).children
					.find(option => option.value === value[3]).label;
				this.outboundData.reviewer = selectedOption;
			},
			//改变仓库获取库位
			async warehouseChange() {
				try {
					const warehouseCode = this.outboundData.warehouseCode;
					const response = await selectLocation(warehouseCode);

					if (Array.isArray(response)) {
						if (this.selectDetailsData) {
							this.selectDetailsData.forEach(item => {
								this.$set(item, 'locationCode', null);
							})
						}
						this.locationData = response.map(item => ({
							value: item.locationCode,
							label: item.locationName
						}))


					} else {
						console.error('Expected an array, but got:', response);
					}
				} catch (error) {
					console.error('Error fetching location:', error);
				}
			},
			//获取商品库存
			async handleLocationChange(row) {
				const query = {
					locationCode: row.locationCode,
					productCode: row.productCode
				}

				await getInventoryNumber(query)
					.then(response => {
						response = response == '' ? 0 : response;
						this.$set(row, 'inventory', response);
					})
					.catch(error => {
						console.error('查询库存失败:', error);
					});
			},

			//本次出库数量
			validateQuantity(row) {
				row.money = row.outboundNumber * row.inPrice;

				this.calculateTotal();
			},

			//获取各部门人员
			async fetchHandle() {
				try {
					const response = await selectAllSysDept();
					if (Array.isArray(response)) {
						this.cascaderOptions = await this.convertToCascaderOptions(response);
					} else {
						console.error('Expected an array, but got:', response);
					}
				} catch (error) {
					console.error('Error fetching items:', error);
				}
			},

			async convertToCascaderOptions(data) {
				if (!Array.isArray(data)) {
					console.error('Expected an array, but got:', data);
					return [];
				}

				// 创建一个映射，用于快速查找父项
				const itemMap = new Map(data.map(item => [item.deptId, item]));
				const topLevelItems = [];

				for (const item of data) {
					if (item.parentId === 0) {
						topLevelItems.push(await this.createOption(item));
					} else {
						const parentItem = itemMap.get(item.parentId);
						if (parentItem) {
							const childItem = await this.createOption(item);
							if (!parentItem.children) {
								parentItem.children = [];
							}
							parentItem.children.push(childItem);
						}
					}
				}

				return topLevelItems;
			},

			async createOption(item) {
				const [children, users] = await Promise.all([
					this.fetchChildren(item.deptId),
					this.fetchUsers(item.deptId)
				]);
				return {
					value: item.deptId,
					label: item.deptName,
					children: children,
					users: users
				};
			},

			async fetchChildren(parentId) {
				try {
					const response = await selectAllSysDeptByID(parentId);
					if (Array.isArray(response)) {
						return Promise.all(response.map(async (item) => {
							const [users, children] = await Promise.all([
								this.fetchUsers(item.deptId),
								this.fetchChildren(item.deptId) // 递归获取子部门
							]);
							return {
								value: item.deptId,
								label: item.deptName,
								children: [
									...children,
									...users.map(user => ({
										value: user.value,
										label: user.label,
										// isUser: true
									}))
								]
							};
						}));
					} else {
						console.error('Expected an array, but got:', response);
						return [];
					}
				} catch (error) {
					console.error('Error fetching children:', error);
					return [];
				}
			},

			async fetchUsers(deptId) {
				try {
					const response = await selectAllSysUserByParentId(deptId);
					if (Array.isArray(response)) {
						return response.map(user => ({
							value: user.userId,
							label: user.userName
						}));
					} else {
						console.error('Expected an array, but got:', response);
						return [];
					}
				} catch (error) {
					console.error('Error fetching users:', error);
					return [];
				}
			},

			//获取仓库
			async fetchWarehouse() {
				try {
					const response = await listWarehouse();
					if (Array.isArray(response.rows)) {
						response.rows.forEach(item => {
							this.warehouseOptions.push({
								'lable': item.warehouseName,
								'value': item.warehouseCode,
							})
						})
					} else {
						console.error('Expected an array, but got:', response);
					}
				} catch (error) {
					console.error('Error fetching warehouse:', error);
				}
			},

			//选择出库类型
			changeType() {
				if (this.outboundData.outboundType == 0) {
					this.resetOut();
					this.resetreOutDetails();
					this.getOdSaleList();
				} else {
					this.resetreturn();
					this.resetreReturnDetails();
					this.getInRejectedList();
				}
				this.selectDetailsData = null;
				this.detailsData = null;
				this.selectDetails = null;
				this.receipts.dataCodes = null;
				this.receipts.selectDataCodes = null;
				this.outboundData.relatedNumber = null;
				this.outboundData.relatedTarget = null;
				this.outboundData.consignee = null;
				this.outboundData.phone = null;
			},
			async getOdSaleList() {
				//销售出库
				try {
					const response = await listOdSale(this.queryParamsOut);
					if (Array.isArray(response.rows)) {
						this.receipts.receipts = response.rows;
						this.receipts.dataTotal = response.total;
					} else {
						console.error('Expected an array, but got:', response);
					}
				} catch (error) {
					console.error('Error fetching users:', error);
				}
			},
			async getInRejectedList() {
				//进货退货
				try {
					const response = await listInRejected(this.queryParamsReturn);
					if (Array.isArray(response.rows)) {
						this.receipts.receipts = response.rows;
						this.receipts.dataTotal = response.total;
					} else {
						console.error('Expected an array, but got:', response);
					}
				} catch (error) {
					console.error('Error fetching users:', error);
				}
			},
			//搜索进货退货单
			handleQueryReturn() {
				this.queryParamsReturn.pageNum = 1;
				this.getInRejectedList();
			},

			//搜索销售出库单
			handleQueryOut() {
				this.queryParamsOut.pageNum = 1;
				this.getOdSaleList();
			},
			//打开单据
			openForm() {
				if (this.outboundData.outboundType == 0)
					this.openOutForm = true;
				else
					this.openReturnForm = true;
			},


			//选择销售单
			handleSelectionOdSale(selection) {
				this.receipts.tempData = selection[0];
			},
			//确定销售单
			handleOdSale() {
				if (this.receipts.tempData == undefined) {
					this.$message({
						message: '请选择销售单！',
						type: 'warning'
					});
					return;
				}
				if (this.receipts.dataCodes != null && this.receipts.dataCodes == this.receipts.tempData.saleCode) {
					this.openOutForm = false;
					return;
				} else {
					this.resetreOutDetails();
					this.selectDetailsData = null;
				}
				this.receipts.dataCodes = this.receipts.tempData.saleCode;
				this.outboundData.relatedNumber = this.receipts.tempData.saleCode;
				this.outboundData.relatedTarget = this.receipts.tempData.customer;
				this.outboundData.consignee = this.receipts.tempData.contacts;
				this.outboundData.phone = this.receipts.tempData.phone;

				this.queryDetails();
				this.openOutForm = false;
			},

			//取消销售单
			closeOdSale() {
				const sale = this.receipts.receipts.find(item => item.saleCode == this.receipts.dataCodes);
				if (sale != undefined) {
					this.$refs.odSaleTable.toggleRowSelection(sale, true);
				}
				this.openOutForm = false;
			},
			//选择退货单
			handleSelectionInRejected(selection) {
				this.receipts.tempData = selection[0];
			},

			//确定退货单
			handleInRejected() {
				if (this.receipts.tempData == undefined) {
					this.$message({
						message: '请选择退货单！',
						type: 'warning'
					});
					return;
				}
				if (this.receipts.dataCodes != null && this.receipts.dataCodes == this.receipts.tempData.prCode) {
					this.openReturnForm = false;
					return;
				} else {
					this.resetreReturnDetails();
					this.selectDetailsData = null;
				}
				this.outboundData.relatedNumber = this.receipts.tempData.prCode;
				this.outboundData.relatedTarget = this.receipts.tempData.supplier;
				this.outboundData.consignee = this.receipts.tempData.contacts;
				this.outboundData.phone = this.receipts.tempData.phone;
				this.receipts.dataCodes = this.receipts.tempData.prCode;
				this.openReturnForm = false;

				this.queryDetails();
			},
			//取消退货单
			closeRejected() {
				const rejected = this.receipts.receipts.find(item => item.prCode == this.receipts.dataCodes);
				if (rejected != undefined) {
					this.$refs.rejectedTable.toggleRowSelection(rejected, true);
				}
				this.openReturnForm = false;
			},

			//禁用单据
			selectIsDisabled(row) {
				if (row.notShipped) {
					if (row.notShipped !== '0')
						return true;
				}
				if (row.saleState === '5' || row.saleState === '6')
					return true;
				if (row.prState === '5' || row.prState === '6')
					return true;
				return false;
			},

			// 单据详情
			async queryDetails() {
				if (this.outboundData.outboundType == 0) {
					this.queryParamsOutDetails.saleDetailsCode = this.receipts.dataCodes;
					listOdSaleDetails(this.queryParamsOutDetails).then(response => {
						response.forEach(item => {
							this.$set(item, 'money', null); //销售金额
							this.$set(item, 'inventory', null); //当前库存
							this.$set(item, 'outboundNumber', null); //本次出库数量
							this.$set(item, 'createDate', null); //生产日期
							this.$set(item, 'batchNumber', null); //批次号
							this.$set(item, 'locationCode', null); //库位编号
							this.$set(item, 'remark', null); //备注
							this.$set(item, 'outboundCode', this.outboundData.outboundCode);
						})
						this.detailsData = response;
					})
				} else {
					try {
						this.queryParamsReturnDetails.prCode = this.receipts.dataCodes;
						const response = await listRejectedDetails(this.queryParamsReturnDetails);
						if (Array.isArray(response)) {
							response.forEach(item => {
								this.$set(item, 'money', null);
								this.$set(item, 'inventory', null);
								this.$set(item, 'outboundNumber', null);
								this.$set(item, 'createDate', null);
								this.$set(item, 'batchNumber', null);
								this.$set(item, 'locationCode', null);
								this.$set(item, 'remark', null);
								this.$set(item, 'outboundCode', this.outboundData.outboundCode);
							})
							this.detailsData = response;
						} else {
							console.error('Expected an array, but got:', response);
						}
					} catch (error) {
						console.error('Error fetching RejectedDetails:', error);
					}
				}
				if (this.selectDetailsData == null) {
					return;
				}
				this.selectDetailsData.forEach(row => {
					this.$refs.detailsTable.toggleRowSelection(row, true);
				});
			},

			//打开商品详细遮罩
			handleDetails() {
				if (this.receipts.dataCodes === null || this.receipts.dataCodes === '')
					return;
				this.openDetails = true;
			},

			//重置销售出库单据条件
			resetOut() {
				this.queryParamsOut.pageNum = 1;
				this.queryParamsOut.pageSize = 10;
				this.queryParamsOut.saelDept = null;
				this.queryParamsOut.saleDate = null;
				this.queryParamsOut.saleCode = null;
				this.queryParamsOut.saleState = null;
				this.queryParamsOut.customer = null;
				this.queryParamsOut.salePerson = null;
			},
			//重置进货退货单据条件
			resetreturn() {
				this.queryParamsReturn.pageNum = 1;
				this.queryParamsReturn.pageSize = 10;
				this.queryParamsReturn.phDate = null;
				this.queryParamsReturn.phDept = null;
				this.queryParamsReturn.phPerson = null;
				this.queryParamsReturn.prCode = null;
				this.queryParamsReturn.prState = null;
				this.queryParamsReturn.supplier = null;
			},
			//重置销售出库详细单据条件
			resetreOutDetails() {
				this.queryParamsOutDetails.productCode = null;
				this.queryParamsOutDetails.unit = null;
				this.queryParamsOutDetails.saleDetailsCode = null;
			},
			//重置进货退货单据条件
			resetreReturnDetails() {
				this.queryParamsReturnDetails.productCode = null;
				this.queryParamsReturnDetails.unit = null;
				this.queryParamsReturnDetails.prCode = null;
			},
			//取消选择订单详细
			cancelSelection() {
				// 清空当前选中状态
				this.$refs.detailsTable.clearSelection();
				// 恢复之前选中的状态
				if (this.selectDetailsData != null) {
					this.selectDetailsData.forEach(row => {
						this.$refs.detailsTable.toggleRowSelection(row, true);
					});
				}

				this.openDetails = false;
			},
			//确定选择订单详细
			enableSelection() {
				this.selectDetailsData = this.tempDetailsData;
				this.openDetails = false;
			},
			//选择订单详细
			handleSelectionDetails(row) {
				this.tempDetailsData = row;
			},

			//监听订单详细选中的行
			handleDetailsChange(selection) {
				this.selectDetails = selection;
				this.calculateTotal();
			},
			//移除商品详细
			removeCheck(row) {
				const array = (row.productCode ? [row.productCode] : row.productCode) || this.selectDetails.map(item =>
					item.productCode);
				this.$modal.confirm('是否确认删除编号为"' + array + '"的数据项？').then(() => {
					array.forEach(value => {
						const product = this.selectDetailsData.find(item => item.productCode == value);
						this.$refs.detailsTable.toggleRowSelection(product, false);
						this.selectDetailsData = this.selectDetailsData.filter(item => item !== product);
					});

					this.$modal.msgSuccess("删除成功");
				}).catch(() => {
					console.log('取消删除......')
				});
			},

			//计算总计
			calculateTotal() {
				if (this.selectDetails == null) {
					return;
				}
				this.outboundData.notShipped = this.selectDetails.reduce((total, row) => total + parseInt(row.notShipped),
					0);
				this.outboundData.shipped = this.selectDetails.reduce((total, row) => total + parseInt(row.shipped), 0);
				this.outboundData.reviewerNumber = this.selectDetails.filter(item => item.outboundNumber > 0)
					.reduce((total, row) => total + parseInt(row.outboundNumber), 0);
				this.outboundData.reviewerMoney = this.selectDetails.filter(item => item.money != null)
					.reduce((total, row) => total + parseFloat(row.money), 0);
			},
			//删除文件之后
			handleRemove(file, fileList) {
				this.fileList = fileList;
			},
			//删除文件之前
			beforeRemove(file, fileList) {
				return this.$confirm(`确定移除 ${ file.name }？`);
			},
			//上传文件
			uploadChange(file, fileList) {
				this.fileList = fileList;
			},
			beforeUpload(file) {
				// 定义允许的文件类型
				const allowedTypes = ['application/msword', 'application/pdf', 'application/x-rar-compressed',
					'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
				];
				// 检查文件类型是否在允许的类型中
				const isAllowedType = allowedTypes.includes(file.type);
				// 检查文件大小是否不超过200MB (200 * 1024 * 1024 bytes)
				const isLt200M = file.size <= 200 * 1024 * 1024;

				if (!isAllowedType) {
					this.$message.error('上传文件只能是 doc, pdf, rar 格式!');
				}
				if (!isLt200M) {
					this.$message.error('上传文件大小不能超过 200MB!');
				}
				return isAllowedType && isLt200M;
			},

		},
		watch: {
			receipts(newValue, oldValue) {
				if (newValue.dataCodes != oldValue.dataCodes) {
					resetreOutDetails();
					resetreReturnDetails();
				}
			},
			selectDetails(newValue, oldValue) {
				if (newValue == null || newValue.length == 0) {
					this.outboundData.notShipped = 0;
					this.outboundData.shipped = 0;
					this.outboundData.reviewerNumber = 0;
					this.outboundData.reviewerMoney = 0;
				}
			},
			outboundData(newValue, oldValue) {

			}
		},

	}
</script>
<style>
	i>.el-icon-check {
		font-size: 16px;
		font-weight: bold;
	}

	.fixed-footer {
		position: fixed;
		bottom: 0;
		left: 100px;

		right: 0;
		padding-left: 1400px;
		padding-top: 20px;
		background-color: #f4f4f4;
		/* 设置底部背景色 */
		z-index: 1000;
		/* 确保底部不被遮挡 */
	}

	.jcxx {
		margin-top: 20px;

	}

	.text {
		font-size: 14px;
	}

	.item {
		margin-bottom: 18px;
	}

	.clearfix:before,
	.clearfix:after {
		display: table;
		content: "";
	}

	.clearfix:after {
		clear: both
	}

	.box-card {
		width: 100%;
		margin-top: 20px;
	}

	.total-row {
		background-color: #f9f9f9;
		/* 背景色 */
		font-weight: bold;
		/* 粗体 */
	}

	.label {
		color: black;
		/* 标签字体颜色 */
		margin-left: 10px;
	}

	.you {
		margin-left: 930px;
	}

	.value {
		color: rgb(227, 139, 50);
		/* 数字字体颜色 */
	}

	/* 如果需要调整对齐方式，可以添加其他样式 */
	.total-row td {
		text-align: left;
		/* 左对齐 */
	}

	.total-row td:last-child {
		text-align: right;
		/* 最后一列右对齐 */
	}

	/* 添加样式以美化绿色对勾 */

	/* 在你的样式文件中 */
	.round-checkbox-table .el-table__header-wrapper .el-checkbox__input {
		border-radius: 50%;
		/* 设置为50%以创建圆角效果 */
	}

	.round-checkbox-table .el-table__body .el-checkbox__input {
		border-radius: 50%;
		/* 设置为50%以创建圆角效果 */
	}
</style>
